<?php
    class Users extends ActiveRecord {
        var $change_pass = false;
        
        function _setup()
        {
            $this->table = DB_PREFIX.'users';
        }
        
        function validate()
        {
            $this->validates_presence_of(array('first_name','last_name','email'));            
            $this->validates_as_email('email');                        
        }
        
        function validate_on_create()
        {
            // make sure they create a password
            $this->validates_presence_of('user_password','user_login');     
            $this->validates_length_of('user_login',5);
            $this->validates_uniqueness_of('user_login');
            $this->validates_uniqueness_of('email');
            $this->validates_length_of('user_password',6);       
            $this->validates_confirmation_of('user_password');
        }
        
        function validate_on_update()        
        {
            // person is attempting to change the password
            if ( $this->change_pass && !empty($this->fields['user_password']) )
            {
                $this->validates_length_of('user_password',6);
                $this->validates_confirmation_of('user_password');
            }
            $this->validates_uniqueness_of('email');
        }
        
        function after_validation()
        {
            // hash the password
            if ( $this->change_pass && !empty($this->fields['user_password']) )
            {
                $this->saved_password = $this->get('user_password');
                $this->set('user_password', create_hash($this->fields['user_password']));
            } else {
                unset($this->fields['user_password']);
            }
        }
                
        // user set up functions
        function after_validation_on_create()
        {
            // send out email to user with the pass and stuff
            use_pixel('ActionMailer.php');
            $mail = new ActionMailer();
            $mail->AddReplyTo('noreply@'.$_SERVER['SERVER_NAME']);
            $mail->Subject = 'User Registration For: '.$_SERVER['SERVER_NAME'];
            $mail->Body = "Here are your credentials for ".
                           $_SERVER['SERVER_NAME'].
                           ".\nUsername: ".$this->get('user_login').
                           " \nPassword: ".$this->saved_password;
            $mail->AddAddress($this->get('email'), $this->get('first_name').' '.$this->get('last_name'));
            if ( !$mail->Send() )
            {
                trigger_error('Registration email could not be sent to: '.$this->get('email').' '.$mail->ErrorInfo,FATAL);
            }
        }
        
        // login functions
        function authenticate($data) 
        {
			$clean = $this->clean_fields($data);
			if ( $this->load('user_password=? and user_login=?',
							array(create_hash($clean['user_password']), $clean['user_login'])) )
			{
				return $this->get('id');
			} else {
				return false;
			}
        }

		// authenticate user credentials stored in cookie
		function authenticate_by_cookie($login,$pass)
		{
			$login = sanitize($login);
			$pass  = sanitize($pass);
			if ( $this->load('user_login=?',array($login)) )
			{
				$pass_check = create_hash(COOKIECRYPTKEY.$this->get('user_password'));
				if ( $pass == $pass_check )
				{
					return ($pass == $pass_check);
				}
			} else {
				return false;
			}
		}
        
        function send_user_password()                                       
        {
            if (!$this->is_loaded()) {
                return false;
            }

            $new_password = substr(md5(time()),0,6);                
            $this->set('user_password',$new_password);
            $this->set('user_password_confirm',$new_password);
            $this->set('pass_key',NULL); // need to kill the pass_key nonce
            $this->change_pass = true;
            $this->save(false);

            use_pixel('ActionMailer.php');
            $mail = new ActionMailer();
            $mail->AddReplyTo('noreply@'.$_SERVER['SERVER_NAME']);
            $mail->Subject = 'Password Reset for: '.$_SERVER['SERVER_NAME'];
            $mail->Body = "Here are your new credentials for ".
                           $_SERVER['SERVER_NAME'].
                           ".\nUsername: ".$user['user_login'].
                           " \nPassword: ".$new_password;
            $mail->AddAddress($this->get('email'), $this->get('first_name').' '.$this->get('last_name') );
            if ( !$mail->Send() )
            {   
                $msg = 'Retrieval email could not be sent to: '.$this->get('email').' '.$mail->ErrorInfo;
                error_log($msg);                 
                trigger_error($msg, FATAL);                
                return false;
            }

            return true;
        }
        
        function send_pass_key()
        {
            if (!$this->is_loaded()) {
                return false;
            }

            // gen a passkey, like a nonce
            $passkey = create_hash(md5(time()));
            $this->set('pass_key',$passkey);
            $this->save(false); // bypass validation

            use_pixel('ActionMailer.php');
            $mail = new ActionMailer();
            $mail->AddReplyTo('noreply@'.$_SERVER['SERVER_NAME']);
            $mail->Subject = 'Password Reset request for: '.$_SERVER['SERVER_NAME'];
            $mail->Body = "Please use this link to reset your password: \nhttp://{$_SERVER['SERVER_NAME']}/login/change_pass?key=$passkey";
            $mail->AddAddress($this->get('email'), $this->get('first_name').' '.$this->get('last_name') );
            if ( !$mail->Send() )
            {   
                $msg = 'Retrieval email could not be sent to: '.$this->get('email').' '.$mail->ErrorInfo;
                error_log($msg);                 
                trigger_error($msg, FATAL);                
                return false;
            }
        }
        
        function get_users_as_list()
        {
            return $this->db->GetAssoc('SELECT id, concat(first_name," ",last_name) fullname FROM `'.$this->table.'` ORDER BY fullname');
        }
        
        function before_delete()
        {
            if ( $this->get('id') == 1 )
            {
                $this->add_error('User Delete Error','You can not delete the admin user');
                return;
            }
        }
        
        function after_delete()
        {
            $user_id = $this->get('id');
            use_model('roles','acl');
            $acl = new Acl();
            $acl->clear_user_access($user_id);
                    
            $roles = new Roles();
            $roles->clear_user_roles($user_id);
        }     
        
        function fullname()
        {
            return $this->get('first_name').' '.$this->get('last_name');
        }   
        
    }

?>